package com.mofang.ticketing.common.core.exception;

import com.mofang.ticketing.common.core.result.IResultCode;
import lombok.extern.slf4j.Slf4j;

import static com.mofang.ticketing.common.core.result.ResultCode.RE_VERIFICATION_ERROR;

/**
 * @author LGC
 */
@Slf4j
public class BizExceptionUtil {

    public static BizException exception(IResultCode resultCode) {
        return exception0(resultCode.getCode(), resultCode.getMsg());
    }

    public static BizException exception(IResultCode errorCode, Object... params) {
        return exception0(errorCode.getCode(), errorCode.getMsg(), params);
    }

    public static BizException exception0(String code, String messagePattern, Object... params) {
        String message = doFormat(code, messagePattern, params);
        return new BizException(code, message);
    }


    /**
     * @param code           错误编号
     * @param messagePattern 消息模版
     * @param params         参数
     * @return 格式化后的提示
     */
    public static String doFormat(String code, String messagePattern, Object... params) {
        StringBuilder sbuf = new StringBuilder(messagePattern.length() + 100);
        int i = 0;
        int j, l;
        for (l = 0; l < params.length; l++) {
            j = messagePattern.indexOf("{}", i);
            if (j == -1) {
                log.error("[doFormat][参数过多：错误码({})|错误内容({})|参数({})", code, messagePattern, params);
                if (i == 0) {
                    return messagePattern;
                } else {
                    sbuf.append(messagePattern.substring(i));
                    return sbuf.toString();
                }
            } else {
                sbuf.append(messagePattern, i, j);
                sbuf.append(params[l]);
                i = j + 2;
            }
        }
        if (messagePattern.indexOf("{}", i) != -1) {
            log.error("[doFormat][参数过少：错误码({})|错误内容({})|参数({})", code, messagePattern, params);
        }
        sbuf.append(messagePattern.substring(i));
        return sbuf.toString();
    }

    public static void main(String[] args) {
        System.out.println(doFormat("1001", "验证码不正确，原因：{}{}", "1752222222", "23433"));
        throw BizExceptionUtil.exception(RE_VERIFICATION_ERROR,"2222222222");
    }
}
